package com.kaohe.web;

import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.Map;

import javax.crypto.interfaces.PBEKey;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.beanutils.BeanUtils;

import com.kaohe.domain.Category;
import com.kaohe.domain.PageBean;
import com.kaohe.domain.Product;
import com.kaohe.service.ProductService;
/**
 * 
 */
@WebServlet("/productServlet")
public class ProductServlet extends BaseServlet {

	private ProductService service=new ProductService();
	
	//查询
	public String pquery(HttpServletRequest request, HttpServletResponse response){
		//接收pageNumber
		String pageNumber = request.getParameter("pageNumber");
		//设置pagesize
		int pageSize=3;
		PageBean<Product> pq=new PageBean<>();
		pq.setPageNumber(Integer.parseInt(pageNumber));
		pq.setPageSize(pageSize);
		//调用service
		PageBean<Product>pcq=service.pquery(pq);
		//存储请求域
		request.setAttribute("pq", pcq);
		//重定向
		return "/admin/product_list.jsp";
		
	}
	
	//添加
	public String addproduct(HttpServletRequest request, HttpServletResponse response) throws IOException{
		try {
			// 1.接收参数
			Map<String, String[]> map = request.getParameterMap();
			// 2.封装数据
			Product product=new Product();
			BeanUtils.populate(product, map);
			// 3.调用service
			service.addproduct(product);
			// 4.重定向查询
			response.sendRedirect(request.getContextPath() + "/productServlet?method=pquery&pageNumber=1");
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}
		
	//修改-跳转页面
	public String toUpdateproduct(HttpServletRequest request, HttpServletResponse response) throws IOException{
			//接收参数
			String pid = request.getParameter("pid");
			//调用
			Product pup=service.toUpdateproduct(pid);
			//存储数据
			request.setAttribute("product", pup);
			//请求转发
			return "/admin/product_update.jsp";
		}				
	//修改数据
	public String update(HttpServletRequest request, HttpServletResponse response) throws IOException{
		try {
			//接收参数
			Map<String, String[]> map = request.getParameterMap();
			//封装
			Product product=new Product();
			BeanUtils.populate(product, map);
			//调用
			service.update(product);
			//重定向
			response.sendRedirect(request.getContextPath() + "/productServlet?method=pquery&pageNumber=1");
		} catch (IllegalAccessException | InvocationTargetException e) {
			e.printStackTrace();
		}
		return null;	
	}
	//删除
	public String deProduct(HttpServletRequest request, HttpServletResponse response) throws IOException{
		//接收参数
		String pid = request.getParameter("pid");
		//调用
		service.deProduct(pid);
		//重定向
		response.sendRedirect(request.getContextPath() + "/productServlet?method=pquery&pageNumber=1");

		return null;
		
	}
		
}
